import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm,Row,Col, Button } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as datetime from '../../utils/datetime'
import dataEditCreate from '../addons/DataEdit'
import dataTableCreate from '../addons/DataTable'
import DataEditTable from '../addons/DataEditTable'
import TIndiClieDiviForm from './TIndiClieDiviForm'
import * as indiDiviService from '../../services/AccountDivi';
const daoName = "TIndiClie";
const ButtonGroup = Button.Group;
const columns = [
  { title: '客户姓名', width: 110, sorter: true, dataIndex: 'Name', key: 'Name', dispaly: true, filter: true },
  { title: '证件类型', width: 110, sorter: true, dataIndex: 'TYNM', key: 'TYNM', dispaly: true, filter: true },
  { title: '证件号码', width: 160, sorter: true, dataIndex: 'IDNO', key: 'IDNO', dispaly: true, filter: true },
  { title: '客户级别', width: 110, sorter: true, dataIndex: 'GDNM', key: 'GDNM', dispaly: true, filter: true },
  { title: '电话号码', width: 110, sorter: true, dataIndex: 'TLNO', key: 'TLNO', dispaly: true, filter: true },
  { title: '地址', width: 250, sorter: true, dataIndex: 'ADDR', key: 'ADDR', dispaly: true, filter: true },
  { title: '邮编', width: 85, sorter: true, dataIndex: 'POCD', key: 'POCD', dispaly: true, filter: true },
];
const columnsDv = [
  { title: '客户姓名', width: 110, sorter: true, dataIndex: 'Name', key: 'Name', dispaly: true, filter: false },
  { title: '证件类型', width: 110, sorter: true, dataIndex: 'TYNM', key: 'TYNM', dispaly: true, filter: false },
  { title: '证件号码', width: 160, sorter: true, dataIndex: 'IDNO', key: 'IDNO', dispaly: true, filter: false },
];
const controls = [
  { name: 'Name', required: true, type: 'text', label: '客户姓名', min: 1, max: 50, grid: 12 / 24 },
  { name: 'TYNM', required: true, type: 'text', min: 1, max: 50, label: '证件类型', grid: 12 / 24 },
  { name: 'IDNO', required: true, type: 'text', label: '证件号码', min: 1, max: 50, grid: 12 / 24 },
  { name: 'GDNM', required: true, type: 'text', min: 1, max: 50, label: '客户级别', grid: 12 / 24 },
  { name: 'TLNO', required: true, type: 'text', label: '电话号码', min: 1, max: 50, grid: 12 / 24 },
  { name: "ADDR", required: true, type: 'text', label: '地址', min: 1, max: 50, grid: 12 / 24 },
  { name: "POCD", required: true, type: 'text', label: '邮编', min: 1, max: 50, grid: 12 / 24 },
];
const columnsFhDivi = [
  { title: 'EMID', sorter: true, key: 'EMID', dataIndex: 'EMID', dispaly: false, filter: false },
  { title: '工号', width: 100, sorter: true, key: 'EMNO', dataIndex: 'EMNO', dispaly: true, filter: true },
  { title: '员工姓名', width: 100, sorter: true, key: 'EMNM', dataIndex: 'EMNM', dispaly: true, filter: true },
  { title: '部门名称', width: 120, sorter: true, key: 'OrganName', dataIndex: 'OrganName', dispaly: true, filter: true },
  { title: '分户比例', width: 100, sorter: true, dataIndex: 'DSVL', key: 'DSVL', dispaly: true, filter: true },
  { title: '分户日期', width: 100, sorter: true, key: 'DSDT', caption: "DSDT", render: data => datetime.format(data.DSDT, "yyyy-MM-dd"), dispaly: true, filter: true, canEdit: true },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class TIndiClieFrom extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      isDivi:false,
      diviDisplay: {
        div1: 'none',
        div2: '',
        lable: '认定',
        isRD: true
      },  
      diviList: {},
      seachData: {},
      seachDataSource: []
    };
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.selectedRowKeys.length !== this.props.selectedRowKeys.length) {
      nextProps.selectedRowKeys.map(key => {
        for (let i = 0; i < nextProps.list.length; i++) {
          if (nextProps.list[i]["NO"] === key) {
            this.state.diviList[key] = { ...nextProps.list[i] };
            break;
          }
        }
      })
    }
  }
  deleteHandle(delDatas) {
    let selkeys = [...this.props.selectedRowKeys]
    for (let j = delDatas.length - 1; j >= 0; j--) {
      const key = delDatas[j]["NO"]
      delete this.state.diviList[key]
      const index = selkeys.indexOf(key)
      if (index !== -1) {
        selkeys.splice(index, 1)
      }
    }
    this.props.dispatch({
      type: `${daoName}/setSelectedRowKeys`,
      payload: { selectedRowKeys: selkeys }
    });
  }  
  addSeachDiviHandler() {
    let dsvl = 0
    let dsdt = "";
    const form = this.refs.TIndiClieDiviForm.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        if (values.EMID !== "" && values.DSVL !== "" && values.DSDT !== "") {
          dsvl = values.DSVL
          dsdt = values.DSDT === !values.DSDT ? null : new Date(values.DSDT.get("year"), values.DSDT.get("month"), 1, 8, 0, 0)
        }
      }
    })
    if (dsvl === "" || dsvl === 0) {
      message.error('分配比例失败！比例不能为空且不能为零,请输入比例！');
      return;
    } else if (dsdt === "") {
      message.error('分配比例失败！日期不能为空,请选择日期！');
      return;
    }
    let data = {
      EMID: this.state.seachData.ID,
      EMNO: this.state.seachData.No,
      EMNM: this.state.seachData.Name,
      OrganName: this.state.seachData.Organization.Name,
      DSVL: dsvl,
      DSDT: dsdt
    }
    let dataSource = this.refs.diviFhTable.state.datas;
    let sumDsvl = 0;
    //验证：添加的员工是否重复，并累加已分配比例是否超出100%
    for (let i = 0; i < dataSource.length; i++) {
      if (Number(dataSource[i]["EMID"]) === Number(data["EMID"])) {
        message.error('分配比例失败！所选员工已分配，请重新选择员工分配！');
        return;
      } else {
        sumDsvl = Number(sumDsvl) + Number(dataSource[i]["DSVL"])
      }
    }
    //验证：已分配比例和新分配比例之和是否超出100%
    let sum = Number(sumDsvl) + Number(data.DSVL)
    if (sum <= 100) {
      dataSource.push(data)
    } else {
      message.error('分配比例失败！已分配比例满足100%或分配比例超出剩余分配比例，请核对分配比例！');
      return;
    }
    this.setState({ seachDataSource: dataSource })
  }
  deleteSeachDiviHandler() {
    const keys = this.refs.diviFhTable.getSelectRowKeys();
    let datas = this.refs.diviFhTable.state.datas;
    let total = this.refs.diviFhTable.state.total;
    let indexs = []
    const keyName = "EMID"
    datas.map((d, k) => {
      for (let i = 0; i < keys.length; i++) {
        if (d[keyName] === keys[i]) {
          indexs.push(k)
          total--
        }
      }
    })
    let delDatas = this.refs.diviFhTable.state.delDatas
    for (let j = indexs.length - 1; j >= 0; j--) {
      const k = indexs[j]
      if (datas[k].$state !== 1) {
        delDatas.push(datas[k])
      }
      datas.splice(k, 1)
    }
    this.setState({ seachDataSource: datas })
  }
  submitSeachDiviHandler() {
    const datas = this.refs.diviFhTable.state.datas;
    const witDividatas = this.refs.diviTable.state.datas;
    if (witDividatas.length <= 0) {
      message.info('请选择要认定的客户!');
      return;
    }
    let dsvlSum = 0;
    let dataSource = []
    datas.map(d => {
      dsvlSum = Number(dsvlSum) + Number(d.DSVL);
      let data = {
        EMID: Number(d.EMID),
        DSDT: d.DSDT,
        DSVL: Number(d.DSVL) / 100
      }
      dataSource.push(data);
    })
    if (dsvlSum !== 100) {
      message.info('占比必须为100%');
      return;
    }
    let cuids = [];
    witDividatas.map(d => cuids.push(Number(d.NO)))
    indiDiviService.clieIndiDivi({ cuids, dataSource }
    ).then(function (data) {
    }).catch(function (ex) {
      console.log('请求出错', ex)
    });
    this.state.diviDisplay.div1 = 'none';
    this.state.diviDisplay.div2 = '';
    this.state.diviDisplay.lable = '认定';
    this.state.diviDisplay.isRD = true;
    this.state.isDivi=false;
    this.state.seachDataSource = [];
    this.state.diviList = {};
    this.props.dispatch({
      type: `${daoName}/setSelectedRowKeys`,
      payload: { selectedRowKeys: [] }
    });
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "NO" }
    });
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20 }
    });
    this.loadOptionData();
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  showDiviHandler() {
    if (this.state.diviDisplay.isRD) {
      this.state.diviDisplay.div1='';
      this.state.diviDisplay.div2='none';  
      this.state.diviDisplay.lable = '返回';
      this.state.diviDisplay.isRD = false;
      this.state.isDivi=true;
    } else {
        this.state.diviDisplay.div1 = 'none';
        this.state.diviDisplay.div2 = '';
        this.state.diviDisplay.lable = '认定';
        this.state.diviDisplay.isRD = true;
        this.state.isDivi=false;
    }
    this.state.diviList = {};
    this.props.dispatch({
        type: `${daoName}/setSelectedRowKeys`,
        payload: { selectedRowKeys: [] }
    });    
  }
  seachHandler(data) {
    this.state.seachData = data;
  }
  showTableHandler() {
    let Name = "";
    let IDNO = "";
    let seeks = [];
    const form = this.refs.TIndiClieFrom.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        if (values.Name === undefined) {
          values.Name = "";
        }
        if (values.IDNO === undefined) {
          values.IDNO = "";
        }
        Name = values.Name;
        IDNO = values.IDNO;
      }
    })
    let whereItems = [];
    let WhereCauses = [];
    if (Name !== "" && IDNO !== "") {
      whereItems.push({
        FieldName: "Name",
        Operator: "like",
        FieldValues: Name
      });
      whereItems.push({
        FieldName: "IDNO",
        Operator: "like",
        FieldValues: IDNO
      })
    } else if (Name !== "" && IDNO === "") {
      whereItems.push({
        FieldName: "Name",
        Operator: "like",
        FieldValues: Name
      });
    } else if (Name === "" && IDNO !== "") {
      whereItems.push({
        FieldName: "IDNO",
        Operator: "like",
        FieldValues: IDNO
      })
    } else {
      whereItems.push({
        FieldName: "Name",
        Operator: "like",
        FieldValues: ""
      });
      whereItems.push({
        FieldName: "IDNO",
        Operator: "like",
        FieldValues: ""
      })
    }
    WhereCauses.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    if (whereItems.length !== 0)
      seeks = WhereCauses;
    else
      seeks = [];
    this.state.diviDisplay.div1 = 'none';
    this.state.diviDisplay.div2 = '';
    this.state.diviDisplay.lable = '认定';
    this.state.diviDisplay.isRD = true;
    this.state.isDivi=false;
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, seeks }
    });
  };
  render() {
    let { showEdit, record } = this.props
    const dsCount = this.state.seachDataSource.length
    const isDisabled = dsCount > 0 ? true : false;
    const controlsCx = [
      { name: 'Name', required: false, type: 'text', label: '客户姓名', grid: 7 / 24, layout: { labelSpan: 8, wrapperSpan: 16 } },
      { name: 'IDNO', required: false, type: 'text', label: '证件号码', grid: 7 / 24, layout: { labelSpan: 6, wrapperSpan: 16 } },
      { name: 'button', required: false, type: 'button-group', grid: 7 / 24, data: [{ value: '1', label: '查询', onClick: this.showTableHandler.bind(this) }, { value: '2', label: this.state.diviDisplay.lable, onClick: this.showDiviHandler.bind(this) }], layout: { labelSpan: 4, wrapperSpan: 20 } },
    ]
    const controlsFhCx = [
      { name: 'EMID', required: true, type: 'search', label: '员工', grid: 5 / 24, layout: { labelSpan: 9, wrapperSpan: 15 }, fetch: { daoName: 'UserSel', searchColumns: ['No', 'Name'],optionTpl: 'Name', valueTpl: "ID", onSelect: this.seachHandler.bind(this) }, dataType: "number", seekType: 2 },
      { name: 'DSVL', required: true, type: 'number', label: '比例%', grid: 4 / 24, layout: { labelSpan: 12, wrapperSpan: 12 }, dataType: 'number' },
      { name: 'DSDT', required: true, type: 'month', label: '月份', grid: 5 / 24, isDisabled: isDisabled, layout: { labelSpan: 9, wrapperSpan: 15 }, dataType: 'month' },
      { name: 'button', required: false, type: 'button-group', grid: 10 / 24, data: [{ value: '1', label: '添加', onClick: this.addSeachDiviHandler.bind(this) }, { value: '2', label: '删除', onClick: this.deleteSeachDiviHandler.bind(this) }, { value: '3', label: '提交', onClick: this.submitSeachDiviHandler.bind(this) }] },
    ]
    let dataList = []
    Object.values(this.state.diviList).forEach(v => dataList.push(v))
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create} style={{ paddingBottom: '-16px' }}>
            <EditFrom ref="TIndiClieFrom" daoName={daoName} controls={controlsCx} record={record} clearItemMargin={true} />
          </div>
          <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls} multiSelect={this.state.isDivi}/>
          <div style={{ display: this.state.diviDisplay.div1 }} id="fhIndiDiviDiv">
            <Row>
              <Col span={9}>
                <DataEditTable columns={columnsDv} ref="diviTable" height={150} dataSource={dataList} keyName={"ID"} daoName={daoName} canDelete={true} onDelete={this.deleteHandle.bind(this)} />
              </Col>
              <Col span={15}>
                <DataEditTable columns={columnsFhDivi} dataSource={this.state.seachDataSource} ref="diviFhTable" height={150} keyName={"EMID"} daoName={"TIndiClieDivi"} footer={false} />
                <EditFrom ref="TIndiClieDiviForm" daoName={daoName} controls={controlsFhCx} record={record} clearItemMargin={true} />
              </Col>
            </Row>
          </div>
          <div style={{ display: this.state.diviDisplay.div2 }} id="showIndiDiviDiv">
            <TIndiClieDiviForm />
          </div>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, list, keyName } = state[daoName];
  return {
    showEdit,
    selectedRowKeys,
    list,
    keyName,
    record
  }
}
TIndiClieFrom = connect(mapStateToProps)(TIndiClieFrom)
export default TIndiClieFrom;

let render = (props) => React.createElement(TIndiClieFrom, props);
let f = new Factory()
f.set("TIndiClieFrom", render)
